﻿using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyAspNetCoreTodo.Datas;
using MyAspNetCoreTodo.Dtos;
using MyAspNetCoreTodo.Identity; 
namespace MyAspNetCoreTodo.Services
{
    public class ApplicationUserService : IApplicationUserService
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly ApplicationDbContext _context; 
        private readonly RoleManager<IdentityRole> _roleManager;
        public ApplicationUserService(UserManager<ApplicationUser> userManager, ApplicationDbContext context, RoleManager<IdentityRole> roleManager)
        {
            _userManager = userManager;
            _context = context;
            _roleManager = roleManager;
        }

        public async Task<bool> CreateTestUser()
        {
            // 生成唯一的用户名和电子邮件地址
            var uniqueId = Guid.NewGuid().ToString("N").Substring(0, 8); // 生成一个 8 位的唯一标识符
            var userName = $"testuser_{uniqueId}@example.com";
            var email = $"testuser_{uniqueId}@example.com";

            var user = new ApplicationUser
            {
                UserName = userName,
                Email = email,
                FirstName = "Test",
                LastName = "User"
            };

            var result = await _userManager.CreateAsync(user, "Password123!");

            if (result.Succeeded)
            {
                // 检查角色是否存在，如果不存在则创建
                var roleName = "TestRole";
                if (!await _roleManager.RoleExistsAsync(roleName))
                {
                    await _roleManager.CreateAsync(new IdentityRole(roleName));
                }

                // 为用户分配角色
                await _userManager.AddToRoleAsync(user, roleName);
            }

            return result.Succeeded;
        }

        public async Task<IEnumerable<ApplicationUserDto>> GetAllUsersAsync()
        {
            return await _context.Users.Select(
                u => new ApplicationUserDto
                {
                    Id = u.Id,
                    UserName = u.UserName,
                    Email = u.Email,
                    FirstName = u.FirstName,
                    LastName = u.LastName
                }

                ).ToArrayAsync() ;
                  
        }

       

        public async Task<ApplicationUserDto> GetUserByIdAsync(string userId)
        {
            var user = await _context.Users.FindAsync(userId);
            if (user == null)
            {
                return null;
            }

            return new ApplicationUserDto
            {
                Id = user.Id,
                UserName = user.UserName,
                Email = user.Email,
                FirstName = user.FirstName,
                LastName = user.LastName
            };

        }

      
    }
}
